﻿
using RBACProject.Application.Role.Dto;
using RBACProject.Domian;
using RBACProject.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RBACProject.Application.Role
{
    /// <summary>
    /// 角色服务层
    /// </summary>
    public class RoleServer: IRoleServer
    {
        private readonly IBaseRepository<RoleModel> Irole;

        private readonly IBaseRepository<UserRoleModel> Iuserrole;

        private readonly IBaseRepository<UserModel> Iuser;

        public RoleServer(IBaseRepository<RoleModel> irole,IBaseRepository<UserRoleModel> iuserrole,IBaseRepository<UserModel> iuser)
        {
            Irole = irole;
            Iuserrole = iuserrole;
            Iuser = iuser;
        }

        /// <summary>
        /// 查询全部角色信息
        /// </summary>
        /// <returns></returns>
        public ResultDto<List<RoleModel>> GetRoleList()
        {
            var list = Irole.QueryAsnycAll();
            return new ResultDto<List<RoleModel>>
            {
                Data = list.ToList(),
                Result = Result.Success,
            };
        }

        /// <summary>
        /// 查询  按主键查
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Task<RoleModel> RoleQueryById(int id)
        {
            var data = Irole.QueryAsnycById(id);
            return data;
        }

        /// <summary>
        /// 用户角色设置
        /// </summary>
        /// <returns></returns>
        public async Task<ResultDto<UserRoleModel>> AddUserRoleInfo(UserRoleModel model)
        { 
            var roleData = Iuserrole.QueryAsnycAll().Where(x=>x.UserId==model.UserId && x.RoleId==model.RoleId);
            if (roleData.Count() > 0) 
            {
                return new ResultDto<UserRoleModel>
                {
                    Result = Result.Failure,
                    Message = "此用户已有该权限！",
                };
            }
            var data = await Iuserrole.InsertAsync(model);
            return new ResultDto<UserRoleModel>
            {
                Result = Result.Success,
                Message = " 用户角色设置成功！",
            };
        }

        /// <summary>
        /// 新增角色信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public  async Task<ResultDto<RoleModel>> AddRoleInfo(RoleModel model)
        {
            var rdata = Irole.QueryAsnycAll().Where(x => x.RoleName == model.RoleName);
            if (rdata.Count() > 0)
            {
                return new ResultDto<RoleModel>
                {
                    Result = Result.Failure,
                    Message = "角色信息重复了,请重新输入...！",
                };
            }
            var data = await Irole.InsertAsync(model);
            return new ResultDto<RoleModel>
            {
                Result = Result.Success,
                Message = "新增角色信息成功！",
            };
        }

        /// <summary>
        /// 删除用户角色信息
        /// </summary>
        /// <param name="id">编号</param>
        /// <returns></returns>
        public async Task<ResultDto<int>> DeleteRole(int id)
        { 
            var entity = await Iuserrole.QueryAsnycById(id);
            entity.IsDeleted= true;
            var  data= await Iuserrole.UpdateAsnyc(entity);
            if (data.IsDeleted==true) 
            {
                return new ResultDto<int>
                {
                    Result = Result.Success,
                    Message = "删除成功"
                };
            }
            else
            {
                return new ResultDto<int>
                {
                    Result = Result.Failure,
                    Message = "删除失败"
                };
            }
        }


        /// <summary>
        /// 查询角色全部数据
        /// </summary>
        /// <param name="roleId">角色编号</param>
        /// <param name="userName">用户名</param>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">页大小</param>
        /// <param name="totalCount">总行数</param>
        /// <param name="totalCount">分页总数</param>
        /// <returns></returns>
        public List<UserRoleDto> GetRoleInfo(int roleId, string userName, int pageIndex, int pageSize, out int totalCount, out int pageCount)
        {
            var userData = Iuser.QueryAsnycAll(); //用户
            var roleData = Irole.QueryAsnycAll();  //角色
            var iuserroleData = Iuserrole.QueryAsnycAll();  ////用户角色关系
            //三表联查
            var query = (from u in userData
                         join ur in iuserroleData
                         on u.UserId equals ur.UserId
                         join r in roleData
                         on ur.RoleId equals r.RoleId
                         where (roleId == 0 || r.RoleId == roleId)
                         && (string.IsNullOrEmpty(userName) || u.UserName.Contains(userName))
                         && (u.IsDeleted == false && ur.IsDeleted == false && r.IsDeleted == false)
                         select new UserRoleDto
                         {
                            URId = ur.URId,
                            RoleId = r.RoleId,
                            RoleName = r.RoleName,
                            Remark = r.Remark,
                            UserId = u.UserId,
                            UserName = u.UserName,
                            FullName = u.FullName,
                            Email = u.Email,
                            Avatar = u.Avatar,
                            CreateTime = ur.CreateTime,
                            UpdateTime= ur.UpdateTime,
                         }).Distinct().AsQueryable();
            totalCount = query.Count();
            pageCount = (int)Math.Ceiling(totalCount * 1.0 / pageSize);
            query = query.OrderBy(x => x.URId).Skip((pageIndex - 1) * pageSize).Take(pageSize);
            return query.ToList();
        }


        /// <summary>
        /// 修改角色信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<ResultDto<RoleModel>> UpdRoleInfo(RoleModel model)
        {
            var rdata = Irole.QueryAsnycAll().Where(x => x.RoleName == model.RoleName);
            if (rdata.Count() > 0)
            {
                return new ResultDto<RoleModel>
                {
                    Result = Result.Failure,
                    Message = "角色信息重复了,请重新输入...！",
                };
            }
            var data = await Irole.UpdateAsnyc(model);
            return new ResultDto<RoleModel>
            {
                Result = Result.Success,
                Message = "修改角色信息成功！",
            };
        }
    }
}
